package net.borderwars.simulator;

import net.borderwars.simulator.events.BEvent;

import java.util.HashSet;
import java.util.logging.Logger;

/**
 * @author Eric
 *         Date: Jul 30, 2005
 *         Time: 9:49:59 PM
 */
public class EventProcessor implements Runnable {
    static private Logger log = Logger.getLogger ("EventProcessor");
    Thread t;
    private EventQueue eq;

    public EventProcessor (EventQueue eq) {
        this.eq = eq;
        t = new Thread (this, "BEvent Processor");
    }

    long lastTime = 0;

    public void run () {
        BEvent e = eq.take ();
        while (e != null) {
            e.setEventQueue (eq);
            notifyPreListeners (e);
            e.process ();
            notifyPostListeners (e);
            e = eq.take ();
        }
    }

    public void start () {
        t.start ();
    }

    public void addEventListener (ProcessEventListener pel) {
        postListeners.add (pel);
        preListeners.add (pel);
    }

    public void addPostProcessEventListener (PostProcessEventListener post) {
        postListeners.add (post);
    }

    public void addPreProcessEventListener (PreProcessEventListener ppel) {
        preListeners.add (ppel);
    }

    public void removeEventListener (ProcessEventListener pel) {
        postListeners.remove (pel);
        preListeners.remove (pel);
    }

    public void removePostProcessEventListener (PostProcessEventListener post) {
        postListeners.remove (post);
    }

    public void removePreProcessEventListener (PreProcessEventListener ppel) {
        preListeners.remove (ppel);
    }

    private HashSet<PostProcessEventListener> postListeners = new HashSet<PostProcessEventListener> ();
    private HashSet<PreProcessEventListener> preListeners = new HashSet<PreProcessEventListener> ();

    private void notifyPostListeners (BEvent e) {
        for (PostProcessEventListener ppel : postListeners) {
            ppel.processedEvent (e);
        }
    }

    private void notifyPreListeners (BEvent e) {
        for (PreProcessEventListener ppel : preListeners) {
            ppel.aboutToProcess (e);
        }
    }

}

